//
//  CYAPIXDetailVC.m
//  CreditAddressBook
//
//  Created by Mosu&Cuu on 16/5/20.
//  Copyright © 2016年 Lee. All rights reserved.
//

#import "CYAPIXDetailVC.h"
#import "APiXCameraView.h"
#import "APiXImgaeToBase64.h"

@interface CYAPIXDetailVC ()<UIImagePickerControllerDelegate,UINavigationControllerDelegate>

@property (nonatomic, strong) APiXCameraView *apixCameraView;
@property (nonatomic, retain) NSString *filePath; //图片2进制路径
@property (nonatomic, strong) NSDictionary *fontDict;
@property (nonatomic, strong) NSDictionary *backDict;
@property (nonatomic, assign) BOOL isfont;

@end

@implementation CYAPIXDetailVC

- (void)viewDidLoad {
    [super viewDidLoad];
    [self.view addSubview:self.apixCameraView];
    [self navagate];
    // Do any additional setup after loading the view from its nib.
}

#pragma -mark 相机相关操作
- (void)openAlibum{
     UIImagePickerController *picker = [[UIImagePickerController alloc] init];
     picker.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
     picker.delegate = self;
     //设置选择后的图片可被编辑
     picker.allowsEditing = NO;
     [self presentViewController:picker animated:YES completion:nil];
     
}

- (void)takPhoto{
     UIImagePickerControllerSourceType sourceType = UIImagePickerControllerSourceTypeCamera;
     if ([UIImagePickerController isSourceTypeAvailable: UIImagePickerControllerSourceTypeCamera])
     {
          UIImagePickerController *picker = [[UIImagePickerController alloc] init];
          
          picker.delegate = self;
          //设置拍照后的图片可被编辑
          picker.allowsEditing = NO;
          picker.sourceType = sourceType;
          [self presentViewController:picker animated:YES completion:nil];
     }else
     {
          NSLog(@"模拟其中无法打开照相机,请在真机中使用");
     }
     
}

//取消选择
- (void)imagePickerControllerDidCancel:(UIImagePickerController *)picker
{
     [picker dismissViewControllerAnimated:YES completion:nil];
}
//当选择一张图片后进入这里
-(void)imagePickerController:(UIImagePickerController*)picker didFinishPickingMediaWithInfo:(NSDictionary *)info
{
     NSString *type = [info objectForKey:UIImagePickerControllerMediaType];
     //当选择的类型是图片
     if ([type isEqualToString:@"public.image"])
     {
          //先把图片转成NSData
          UIImage * image = [info objectForKey:UIImagePickerControllerOriginalImage];
          UIImageWriteToSavedPhotosAlbum(image, nil, nil, nil);
          NSData *data;
          if (UIImagePNGRepresentation(image) == nil)
          {
               data = UIImageJPEGRepresentation(image, 0.75);
          }
          else
          {
               data = UIImageJPEGRepresentation(image,0.75);
          }
          //这里将图片放在沙盒的documents文件夹中
          NSString * DocumentsPath = [NSHomeDirectory() stringByAppendingPathComponent:@"Documents"];
          //文件管理器
          NSFileManager *fileManager = [NSFileManager defaultManager];
          //把刚刚图片转换的data对象拷贝至沙盒中 并保存为image.png
          [fileManager createDirectoryAtPath:DocumentsPath withIntermediateDirectories:YES attributes:nil error:nil];
          [fileManager createFileAtPath:[DocumentsPath stringByAppendingString:@"/image.png"] contents:data attributes:nil];
          //得到选择后沙盒中图片的完整路径
          _filePath = [[NSString alloc]initWithFormat:@"%@%@",DocumentsPath,  @"/image.png"];
          //关闭相册界面
          [picker dismissViewControllerAnimated:YES completion:nil];
          NSLog(@"文件的路径是%@",_filePath);
          UIImage *sizeImage = [APiXImgaeToBase64 OriginImage:[UIImage imageWithContentsOfFile:_filePath] scaleToSize: CGSizeMake(self.apixCameraView.avaterImageView.frame.size.width*3, self.apixCameraView.avaterImageView.frame.size.height*3)];
          self.apixCameraView.avaterImageView.image = sizeImage;
     }
     
}

- (void)recogine:(KButtonType)kButtonType{
     if ([_filePath isEqualToString:@""]) {
          return;
     }
     UIImage  *image = [UIImage imageWithContentsOfFile:_filePath];
     NSString *baseString = [APiXImgaeToBase64 image2DataURL:[APiXImgaeToBase64 imageCompressForWidth:image targetWidth:(SCREEN_WITH-24)*2]];
     NSString *mineType = [APiXImgaeToBase64 mimeType:image];
     NSString *cmd = nil;
     
     if (kButtonType == KButtonTypeBack) {
          cmd = @"idcard_back";
          self.isfont = NO;
     }
     if (kButtonType == KButtonTypeFont) {
          cmd = @"idcard_front";
          self.isfont = YES;
          
     }
     [self recognize:cmd withBaseSting:baseString andMineType:mineType];
}

#pragma -mark 识别部分
- (void)recognize:(NSString *)cmd withBaseSting:(NSString *)baseString andMineType:(NSString *)mineType{
     NSString *httpUrl = @"http://a.apix.cn/apixlab/idcardrecog/idcardimage";
     NSDictionary *param = @{@"cmd":cmd,
                             @"pictype":mineType,
                             @"pic":baseString};
     [self request: httpUrl withHttpArg: param];
}

/**
 *  图像识别的网络请求，可以使用自己的的网络库，这里只是做一个示例
 *
 *  @param httpUrl 请求地址
 *  @param param 参数
 */
-(void)request: (NSString*)httpUrl withHttpArg: (NSDictionary*)param{
     NSURL *url = [NSURL URLWithString: httpUrl];
     NSMutableURLRequest *request = [[NSMutableURLRequest alloc]initWithURL: url cachePolicy: NSURLRequestUseProtocolCachePolicy timeoutInterval: 10];
     [request setHTTPMethod: @"POST"];
     
     //购买之后，你自己的apix-key在调试界面下面
     [request addValue: @"77a934ad16d8421d7cbbed1b3a214763" forHTTPHeaderField: @"apix-key"];
     [request addValue: @"application/x-www-form-urlencoded" forHTTPHeaderField: @"Content-Type"];
     NSData *data = [NSJSONSerialization dataWithJSONObject:param options:NSJSONWritingPrettyPrinted error:nil];
     [request setHTTPBody: data];
     __weak typeof(self) weakself = self;
     [NSURLConnection sendAsynchronousRequest: request
                                        queue: [NSOperationQueue mainQueue]
                            completionHandler: ^(NSURLResponse *response, NSData *data, NSError *error){
                                 if (error) {
                                      NSLog(@"Httperror: %@%ld", error.localizedDescription, error.code);
                                 } else {
                                      NSInteger responseCode = [(NSHTTPURLResponse *)response statusCode];
                                      NSString *responseString = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
                                      NSLog(@"HttpResponseCode:%ld", responseCode);
                                      NSLog(@"HttpResponseBody %@",responseString);
                                      NSJSONSerialization *json = [NSJSONSerialization JSONObjectWithData:data options:0 error:nil];
                                      NSDictionary *dicjson = (NSDictionary *)json;
                                      NSLog(@"%@",dicjson);
                                      if (self.isfont) {
                                           self.fontDict = dicjson;
                                      }else{
                                           self.backDict = dicjson;
                                      }
                                      [weakself refresh];
                                 }
                            }];
}

#pragma -mark refresh
- (void)refresh{
     if (self.isfont&&([self.fontDict[@"state"] intValue]==1)) {
          NSDictionary *data = self.fontDict[@"data"];
          self.apixCameraView.nameLabel.text = [NSString stringWithFormat:@"姓名:%@",data[@"name"]];
          self.apixCameraView.nationLabel.text = [NSString stringWithFormat:@"民族:%@",data[@"nation"]];
          self.apixCameraView.sexLabel.text = [NSString stringWithFormat:@"性别:%@",data[@"sex"]];
          self.apixCameraView.addressLabel.text = [NSString stringWithFormat:@"地址:%@",data[@"address"]];
          self.apixCameraView.idLabel.text = [NSString stringWithFormat:@"身份证号:%@",data[@"number"]];
          //生日根据身份证号来判断
          NSString *birth = data[@"number"];
          birth = [birth substringFromIndex:6];
          birth = [birth substringToIndex:8];
          NSMutableString *mutableString = [NSMutableString stringWithFormat:@"%@",birth];
          [mutableString insertString:@"." atIndex:4];
          [mutableString insertString:@"." atIndex:7];
          self.apixCameraView.brithLabel.text = [NSString stringWithFormat:@"出生:%@",mutableString];;
          
     }else if(!self.isfont&&([self.backDict[@"state"] intValue]==1)){
          NSDictionary *data = self.backDict[@"data"];
          
          NSMutableString *fromString = [NSMutableString stringWithFormat:@"%@",data[@"date1"]];
          [fromString insertString:@"." atIndex:4];
          [fromString insertString:@"." atIndex:7];
          
          NSMutableString *toString = [NSMutableString stringWithFormat:@"%@",data[@"date2"]];
          [toString insertString:@"." atIndex:4];
          [toString insertString:@"." atIndex:7];
          self.apixCameraView.validLabel.text = [NSString stringWithFormat:@"有效期:%@-%@",fromString,toString];
          self.apixCameraView.signAuthorityLabel.text = [NSString stringWithFormat:@"发证机关:%@",data[@"office"]];
     }
}

#pragma -mark init UI
- (APiXCameraView *)apixCameraView{
     if (!_apixCameraView) {
          _apixCameraView = [[APiXCameraView alloc] initWithFrame:CGRectMake(0, 80, [UIScreen mainScreen].bounds.size.width, [UIScreen mainScreen].bounds.size.height)];
          _apixCameraView.backgroundColor = [UIColor whiteColor];
          __weak typeof(self) weakself = self;
          [_apixCameraView setActionBlock:^(KButtonType kButtonType) {
               [weakself recogine:kButtonType];
          }];
     }
     return _apixCameraView;
}

- (void)navagate{
     self.title  = @"身份证拍照识别";
     self.navigationController.navigationBar.backgroundColor = [UIColor blackColor];
     UIButton *leftbutton = [[UIButton alloc] initWithFrame:CGRectMake(0, 0, 30, 40)];
     [leftbutton setTitle:NSLocalizedString(@"相册", nil) forState:UIControlStateNormal];
     leftbutton.titleLabel.font = [UIFont systemFontOfSize:14];
     [leftbutton setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
     [leftbutton addTarget:self action:@selector(openAlibum) forControlEvents:UIControlEventTouchUpInside];
     self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:leftbutton];
     UIButton *rightbutton = [[UIButton alloc] initWithFrame:CGRectMake(0, 0, 30, 40)];
     [rightbutton setTitle:NSLocalizedString(@"拍照", nil) forState:UIControlStateNormal];
     rightbutton.titleLabel.font = [UIFont systemFontOfSize:14];
     [rightbutton setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
     [rightbutton addTarget:self action:@selector(takPhoto) forControlEvents:UIControlEventTouchUpInside];
     self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:rightbutton];
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
